import threading
import utils
from login import Lighthouse


class WeChatClient:

    def __init__(self, login_service, url='https://mp.weixin.qq.com'):
        """
        通过灯塔登录接口获取公众号后台资料
        :param Lighthouse login_service:
        """
        self.url = url
        self.login = login_service
        self.session = utils.requests_retry_session()
        self.gh_id = None
        self.gh_nickname = None
        self.token = None
        self.index_url = None
        self.index_response = None
        self.violation_list = []

    def log_line(self, msg, gh_nickname=None, gh_id=None):
        line = '[{}]({}) {}'.format(gh_nickname if gh_nickname else self.gh_nickname,
                                    gh_id if gh_id else self.gh_id, msg)
        print(line)
        return line

    def log_err(self, err, logtype='log', gh_nickname=None, gh_id=None):
        utils.log_error(gh_id, logtype)

    def enter(self, gh_id, gh_nickname, pwd):
        cookies = self.login.get_wx_cookie(gh_id)
        if cookies:
            self.log_line('获取Cookie成功', gh_nickname, gh_id)
        else:
            self.log_err('一键登录状态异常，使用人工扫码登录', gh_nickname=gh_nickname, gh_id=gh_id)


def collect(login_service, account):
    srv = WeChatClient(login_service)
    if not srv.enter(account['gh_id'], account['nickname'], account['pwd']):
        return


class CollectThread(threading.Thread):
    def __init__(self, srv, data):
        threading.Thread.__init__(self)
        self.service = srv
        self.account = data

    def run(self):
        collect(self.service, self.account)
